﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using Acando.Dynamics.CRM.Silverlight.Library.Extensions;
using Acando.Dynamics.CRM.Silverlight.Library.Types;
using Acando.Dynamics.CRM.Silverlight.Library.Helper;
using Acando.Dynamics.CRM.Silverlight.Library.Dialogs;

namespace RiaCrm.Sitemap
{
    
    public partial class SitemapView : UserControl
    {
        private SitemapViewModel _viewmodel;
        

        /* Constructor */
        public SitemapView(SitemapViewModel viewmodel)
        {
            InitializeComponent();

            viewmodel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(viewmodel_PropertyChanged);
            this._viewmodel = viewmodel;
            this._viewmodel.LoadSiteMap();
        }

        void viewmodel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "SitemapAsXml")
            {
                var areaNodeList = this.extractSitemapXml();

                foreach (var areaNode in areaNodeList)
                    this.fillBoundTree(tree.Items, areaNode);
            }
        }

        private void fillBoundTree(ItemCollection itemColl, TreeNode node)
        {
            TreeViewItem tvItem = new TreeViewItem();
            tvItem.Selected += new RoutedEventHandler(tvItem_Selected);
            itemColl.Add(tvItem);
            tvItem.DataContext = node;
            tvItem.Header = new TreeViewNode();

            foreach (var child in node.Children)
                this.fillBoundTree(tvItem.Items, child);
        }

        void tvItem_Selected(object sender, RoutedEventArgs e)
        {
            var node = ((TreeViewItem)sender).Header as TreeViewNode;
            String nodeName = node.nodeName.Text;
            //String nodeDepth = node.nodeDepth.Text;
            int nodeDepth = Convert.ToInt16(node.nodeDepth.Text.ToString());

            if(node.IsTopLeadNode)
                this._viewmodel.TreeNodeSelectedCommand.Execute(nodeName);
        }

        private List<TreeNode> extractSitemapXml()
        {
            XElement root = XElement.Parse(this._viewmodel.SitemapAsXml);
            
            # region create query
            var query = from area in root.Elements("Area")
                        select new
                        {
                            Id = area.Attribute("Id").Value,
                            ResourceId = area.Attribute("ResourceId").Value,
                            Groups = new
                            {
                                ListOfGroups = (from area_group in area.Elements("Group")
                                                select new
                                                {
                                                    Id = area_group.Attribute("Id").Value,
                                                    ResourceId = (area_group.Attribute("ResourceId") != null) ? area_group.Attribute("ResourceId").Value : null,
                                                    DescriptionResourceId = (area_group.Attribute("DescriptionResourceId") != null) ? area_group.Attribute("DescriptionResourceId") : null,
                                                    IsProfile = (area_group.Attribute("IsProfile") != null) ? area_group.Attribute("IsProfile").Value : null,
                                                    Subareas = new
                                                    {
                                                        ListOfSubAreas = (from subarea in area_group.Elements("SubArea")
                                                                          select new
                                                                          {
                                                                              Id = subarea.Attribute("Id").Value,
                                                                              Entity = (subarea.Attribute("Entity") != null) ? subarea.Attribute("Entity").Value : null,
                                                                              Privileges = new
                                                                              {
                                                                                  ListOfPrivileges = (from privilege in subarea.Elements("Privilege")
                                                                                                      where privilege.Attribute("Entity") != null
                                                                                                      select new
                                                                                                      {
                                                                                                          Entity = privilege.Attribute("Entity").Value
                                                                                                      }).ToList()
                                                                              }
                                                                          }).ToList()
                                                    }
                                                }).ToList()
                            }
                        };

            # endregion

            // --> http://silverlight.net/blogs/jesseliberty/archive/2009/01/30/the-tree-view-control.aspx

            List<TreeNode> treeNodeList = new List<TreeNode>();

            foreach (var area in query.ToList())
            {
                TreeNode areaNode = new TreeNode();

                areaNode.Name = area.ResourceId.ToString().Replace("Area_", "");

                foreach (var group in area.Groups.ListOfGroups)
                {
                    //if (group.IsProfile != null || (!Convert.ToBoolean(group.IsProfile)) ) 
                    if (!Convert.ToBoolean(group.IsProfile))
                    {
                        TreeNode groupNode = areaNode.CreateChild(group.Id.ToTitle());
                        
                        foreach (var subarea in group.Subareas.ListOfSubAreas.Where(c=> c.Entity.IsNotNull()))
                        {
                            TreeNode subNode = groupNode.CreateChild(subarea.Entity.ToTitle());
                            subNode.isTopLead = true;
                        }
                    }
                }

                treeNodeList.Add(areaNode);
            }

            return treeNodeList;
            
        }
    }
}
